<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Requests\StaffRequest;
use App\Http\Controllers\Controller;
use App\Http\Controllers\LayuiController as Layui;
use App\Models\User;
use App\Models\UserAccount;
use App\Models\Order;
use App\Models\UserInvite;
use App\Models\AccountLog;
use App\Models\UserDepartment;
use App\Models\UserPosition;
use Illuminate\Support\Facades\DB;
use App\Exceptions\FormException;
use Illuminate\Support\Facades\View;
use App\Services\DreamBoxService;

class StaffController extends Controller
{

    private $box_service;

    public function __construct()
    {
        $this->box_service = new DreamBoxService();
    }

    /**
     * 列表页面
     *
     * @Author   qizhifei
     * @DateTime 2019-05-29
     * @return   [type]     [description]
     */
    public function index()
    {
        return view('Admin.staff.index');
    }

    /**
     * 获取数据
     * @param  Request $request [请求参数]
     * @return [json]           [数组格式]
     */
    public function table(Request $request)
    {
        $payload = $request->all();
        //关联模型查询
        $preData = User::with(['userAccountInfo', 'userDepartment', 'userPosition',])
            //->withCount(['userHasInvite'])
            ->when((isset($payload['department']) && $payload['department'] != ''), function ($query) use ($payload) {
                $query->whereHas('userDepartment', function ($query) use ($payload) {
                    $query->Where('id', $payload['department']);
                });
            })
            ->where(function ($query) use ($payload) {
                if (isset($payload['realname']) && $payload['realname'] != '') {
                    $query->Where('realname', 'like', "%$payload[realname]%");
                }
                if (isset($payload['id']) && $payload['id'] != '') {
                    $query->Where('id', 'like', "%$payload[id]%");
                }
                if (isset($payload['phone']) && $payload['phone'] != '') {
                    $query->Where('phone', 'like', "%$payload[phone]%");
                }
                if (isset($payload['status']) && $payload['status'] != '') {
                    $query->Where('status', 'like', "%$payload[status]%");
                }
            })
            ->where('user_type', User::STAFF)
            ->orderBy('id', 'desc')
            ->paginate($request->get('limit', 10));

        $data = $preData->map(function ($item) {
            $item->sex_name = is_null($item->sex) ? '' : ($item->sex == 1 ? '男' : '女'); //性别
            $item->position_name = isset($item->userPosition->position_name) ? $item->userPosition->position_name : ''; //职位名称
            $item->department_name = isset($item->userDepartment->department_name) ? $item->userDepartment->department_name : ''; //部门名称

            $coin_consh = $this->box_service->coin_consh($item->openid); //获取贝壳以及八贝币
            $item->money_consh = $coin_consh['ke'] ? round($coin_consh['ke'], 2) : 0 ; //贝壳余额
            $item->status_name = User::USER_STATUS[$item->status]; //状态

            $item->user_has_invite_count = User::where(['inviter_user_id' => $item->id,'is_real'=>1])->count();
            $userHasOrder = $item->userHasOrder;
            $item->order_num = collect($userHasOrder)->count();
            $item->total_real_pay = is_null($userHasOrder) ? 0 : collect($userHasOrder)->sum('real_pay');


            return $item;
        });

        return Layui::tableJson($preData, 0, $preData->total());
    }


    /**
     * 添加页面
     *
     * @Author   qizhifei
     * @DateTime 2019-05-29
     * @param    Request $request [description]
     * @return   [type]              [description]
     */
    public function create()
    {
        if (View::exists('Admin/staff/add')) {
            return view('Admin/staff/add');
        } else {
            return 'View Not Found';
        }
    }

    /**
     * 添加请求
     *
     * @Author   qizhifei
     * @DateTime 2019-05-29
     * @param    Request $request [description]
     * @return   [type]              [description]
     */
    public function store(StaffRequest $request)
    {
        $payload = $this->packageData($request);
        try {
            if(!empty($payload['openid'])){
                $userInfo = User::where('openid', '=', $payload['openid'])->firstOrFail();
                if(is_null($userInfo) || !$userInfo){
                    return $this->getResponse("保存失败,请正确填写openid",'',400);
                    exit();
                }else{
                    $userInfo->realname = $payload['realname'];
                    $userInfo->sex = $payload['sex'];
                    $userInfo->department = $payload['department'];
                    $userInfo->position = $payload['position'];
                    $userInfo->phone = $payload['phone'];
                    $userInfo->status = $payload['status'];
                    $userInfo->number = $payload['number'];
                    $userInfo->user_type = $payload['user_type'];
                    $userInfo->save();
                }
            }else{
                return $this->getResponse("保存失败,请正确填写openid2",'',400);
                exit();
            }

        } catch (\Exception $exception) {
            throw new FormException(\App::environment('local') ? $exception->getMessage() : '保存失败,请正确填写openid');
        }
        return $this->getResponseSuccess('保存成功', route('staff.index'));
    }


    /**
     * 编辑页面
     *
     * @Author   qizhifei
     * @DateTime 2019-05-31
     * @param    StaffRequest $request [description]
     * @return   [type]                [description]
     */
    public function edit($id)
    {
        if (View::exists('Admin/staff/edit')) {
            $data = User::find($id);
            return view('Admin/staff/edit', compact('data'));
        } else {
            return 'View Not Found';
        }
    }

    /**
     * 修改请求
     *
     * @Author   qizhifei
     * @DateTime 2019-05-31
     * @param    StaffRequest $request [description]
     * @return   [type]                [description]
     */
    public function update(StaffRequest $request)
    {
        $payload = $this->packageData($request);
        try {
            User::where(['openid' => $request->input('openid')])->update($payload);
        } catch (\Exception $exception) {
            throw new FormException(\App::environment('local') ? $exception->getMessage() : '保存失败');
        }
        return $this->getResponseSuccess('保存成功', route('staff.index'));
    }


    /**
     * 拼装共用请求的数据
     *
     * @Author   qizhifei
     * @DateTime 2019-05-31
     * @param    [type]     $request [description]
     * @return   [type]              [description]
     */
    public function packageData($request)
    {
        $payload = $request->all(['realname', 'sex', 'department', 'position', 'phone', 'status', 'wechat', 'openid']);
        $payload['number'] = $this->generatedMember();
        $payload['user_type'] = User::STAFF;
        $payload['status'] = isset($payload['status']) ? $payload['status'] : 2;
        return $payload;
    }

    /**
     * 查看详情
     *
     * @Author   qizhifei
     * @DateTime 2019-05-31
     * @param    [type]     $id [description]
     * @return   [type]         [description]
     */
    public function show($id)
    {
        $preData = User::with(['userAccountInfo', 'userDepartment', 'userPosition'])
            ->where('id', $id)
            ->first();
        //查出会员关系
/*        $register_user_id = UserInvite::where(['inviter_user_id' => $id])
            ->select(DB::raw('group_concat(register_user_id) as ids'))
            ->first()
            ->toArray();*/

        $register_user_id = User::where(['inviter_user_id' => $id,'is_real'=>1])
            ->get()
            ->pluck('id')
            ->toArray();

        //查出关联订单
        $userOrder = Order::
        //where('status', '=', Order::STATUS_SUCCESS)->
        whereIn('user_id', $register_user_id)
            ->get();

        $totalRecharge = AccountLog::where(['status' => 1, 'type' => 1])
            ->whereIn('user_id', $register_user_id)
            ->sum('money');

        $preData->status_name = User::USER_STATUS[$preData->status]; //性别
        $preData->department_name = is_null($preData->userDepartment) ? '' : $preData->userDepartment->department_name;//部门
        $preData->position_name = is_null($preData->userPosition) ? '' : $preData->userDepartment->position_name;//部门
        $preData->money_recharge = is_null($preData->userAccountInfo) ? '' : round($preData->userAccountInfo->money_recharge, 2);//充值余额

        $coin_consh = $this->box_service->coin_consh($preData->openid); //获取贝壳以及八贝币
        $preData->money_eight_consh = $coin_consh['bi'] ? round($coin_consh['bi'], 2) : 0; //八贝币余额
        $preData->money_consh = $coin_consh['ke'] ? round($coin_consh['ke'], 2) : 0 ; //贝壳余额
        $preData->register_user_count = count($register_user_id); //会员数
        $preData->orderCount = count($userOrder); //会员订单数
        $preData->total_real_pay = collect($userOrder)->sum('real_pay'); //会员交易完成订单金额
        $preData->total_recharge = round($totalRecharge, 2); //会员交易完成订单金额

        return view('Admin.staff.show', ['data' => $preData]);
    }

    /**
     * 生成会员ID（m_+4随机数+timestamp组合）\r\nm_88881557969240
     *
     * @Author   qizhifei
     * @DateTime 2019-05-30
     * @return   [type]     [description]
     */
    public function generatedMember()
    {
        return 'm_' . mt_rand(1000, 9999) . time();
    }


    /**
     * 查出邀请的会员信息
     *
     * @Author   qizhifei
     * @DateTime 2019-05-31
     * @param    [type]     $id [description]
     * @return   [type]         [description]
     */
    public function registerUser($id, Request $request)
    {
        //查出会员关系
/*        $register_user_id = UserInvite::where(['inviter_user_id' => $id])
            ->select(DB::raw('group_concat(register_user_id) as ids'))
            ->first()
            ->toArray();*/
        $preData = User::with(['userAccountInfo'])
            ->where(['inviter_user_id' => $id,'is_real'=>1])
            //->whereIn('id', explode(',', $register_user_id['ids']))
            ->orderBy('id', 'desc')
            ->paginate($request->get('limit', 10));

/*        $preData = User::with(['userAccountInfo'])
                    ->whereIn('id', explode(',', $register_user_id['ids']))
                    ->orderBy('id', 'desc')
                    ->paginate($request->get('limit', 10));*/


        $data = $preData->map(function ($item) {
            $item->avatar = "<img src='$item->avatar' >"; //头像
            $item->user_level_name = ($item->userAccountInfo && $item->userAccountInfo->user_level_id) ? UserAccount::LEVEL[$item->userAccountInfo->user_level_id] : ''; //会员等级
            $item->sex_name = $item->sex ? User::SEX_TYPE[$item->sex] : '' ; //性别
            $item->info = "$item->nickname <br> $item->number "; //会员信息
            return $item;
        });

        return Layui::tableJson($preData, 0, $preData->total());
    }


    /**
     * 查看会员充值记录
     *
     * @Author   qizhifei
     * @DateTime 2019-05-31
     * @param    [type]     $id [description]
     * @return   [type]         [description]
     */
    public function recharge($id, Request $request)
    {
        //查出会员关系
        $ids = UserInvite::where(['inviter_user_id' => $id])
            ->select(DB::raw('group_concat(register_user_id) as ids'))
            ->first()
            ->toArray();

        $preData = AccountLog::with(['userInfo'])
            ->whereHas('userInfo', function ($query) use ($ids) {
                $query->whereIn('id', explode(',', $ids['ids']));
            })
            ->where(function ($query) {
                $query->Where('status', '=', 1);
                $query->Where('type', '=', 1);
            })
            ->orderBy('id', 'desc')
            ->paginate($request->get('limit', 10));
        return Layui::tableJson($preData, 0, $preData->total());
    }


    /**
     * 查看会员订单
     *
     * @Author   qizhifei
     * @DateTime 2019-06-01
     * @param    [type]     $id [description]
     * @return   [type]         [description]
     */
    public function orderList($id, Request $request)
    {
        $payload = $request->all();

        //查出会员关系
        $register_user_id = UserInvite::where(['inviter_user_id' => $id])
            ->select(DB::raw('group_concat(register_user_id) as ids'))
            ->first()
            ->toArray();

        $preData = Order::with(['OrderGoods'])
            ->when((isset($payload['name']) && $payload['name'] != ''), function ($query) use ($payload) {
                $query->whereHas('User', function ($query) use ($payload) {
                    //此处搜索的是真实姓名和手机号
                    $query->Where('phone', 'like', "%$payload[name]%")
                        ->orWhere('realname', 'like', "%$payload[name]%");
                });
            })
            ->orderBy('updated_at', 'desc')
            ->when(isset($register_user_id), function ($query) use ($register_user_id) {
                //where('status', '=', Order::STATUS_SUCCESS)->
                $query->whereIn('user_id', explode(',', $register_user_id['ids']));
            })
            ->when(isset($payload['type']), function ($query) use ($payload) {
                $query->Where('order_type', $payload['type']);
            })
            ->when(isset($payload['status']), function ($query) use ($payload) {
                $query->Where('status', $payload['status']);
            })
            ->when(isset($payload['pay_type']), function ($query) use ($payload) {
                $query->Where('pay_type', $payload['pay_type']);
            })
            ->paginate($request->get('limit', 30));

        $data = $preData->map(function ($item) {
            $item->pay_type_name = $item->pay_type ? Order::PAY_TYPE[$item->pay_type] : '';
            $item->status_name = Order::STSTUS[$item->status];
            $item->express_string = $item->order_type == Order::TYPE_ONLINE ? $item->express_name . '<br>' . $item->express_order : '不需要配送';
            if (isset($item->OrderGoods)) {
                $shop_string = '';
                foreach ($item->OrderGoods as $k => $v) {
                    $shop_string .= '<img src="' . $v->photo . '" alt="" width="30px" height="30px">' . $v->title . ' ✖️ ' . $v->amount;
                }
            }
            $item->shop_string = $shop_string;
            return $item;
        });

        return Layui::tableJson($data, 0, $preData->total());
    }


}
